package com.atguigu.testsso.server.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@Controller
public class loginController {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }

    @GetMapping("/person")
    public String person(HttpSession session){
        Object username = session.getAttribute("username");
        if (username==null){
            System.out.println("session为空");
            return "hello";
        }

        return "person";
    }

    @GetMapping("/sso")
    public String sso(@RequestParam("url") String url,
                      @CookieValue(value = "sso_token",required = false) String token,
                      Model model){
        System.out.println(url);
        //判断是否携带cookie，决定该浏览器之前是否在别的服务登陆过
        if (!StringUtils.isEmpty(token)){
            //token不为空，在别的服务登陆过
            return "redirect:"+url+"?sso_token="+token;
        }else {
            //token为空，该浏览器第一次登录 转到登录页进行登录
            model.addAttribute("url",url);
            return "login";
        }
    }

    @PostMapping("/login.html")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        @RequestParam("url") String url,
                        HttpServletResponse response){
        if (!StringUtils.isEmpty(username)&&!StringUtils.isEmpty(password)){
            String token = UUID.randomUUID().toString().replace("-", "");
            stringRedisTemplate.opsForValue().set(token,username);
            Cookie sso_token = new Cookie("sso_token", token);
            response.addCookie(sso_token);
            return "redirect:"+url+"?sso_token="+token;
        }
        return "login";

    }

}
